 <?php 
/* 
Template Name: process ajax
*/
?>
 <?php 
 $id_may=$_POST["id"];
           

include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php' );
 $base_url=get_bloginfo('template_directory'); 

            global $current_user;
            get_currentuserinfo();
            $id_user=$current_user->ID;
            //GET ID user login systems

         global $wpdb;
         $sql= "SELECT wp_lich.*,wp_users.*
                FROM wp_lich
                INNER JOIN wp_users
                ON wp_lich.ID = wp_users.ID
                JOIN wp_may
                ON wp_lich.id_may = wp_may.id_may
                WHERE wp_lich.id_may=".$id_may;
                
         $arr_lich = $wpdb->get_results($sql);

              
              //echo $sql;
              //echo $arr_lich->ID;
              //echo "<br/>";
              //echo "<pre>";
                //var_dump($arr_lich);
                //echo "</pre>";
?>


  <div id='calendar'></div>


  <div id="event_edit_container">
    <form>
      <input type="hidden" />
      <ul>
        <li>
          <span> </span><span class="date_holder"></span> 
        </li>
        <li style="display:none;" >
          
           <label for="title">Máy ID : </label><input type="text" id="id_may" value="<?php echo $id_may; ?>" />
        </li>
        <li>
          <label for="start">Thời gian bắt đầu : </label><select name="start"><option value="">Select Start Time</option></select>
        </li>
        <li>
          <label for="end">Thời gian kết thúc : </label><select name="end"><option value="">Select End Time</option></select>
        </li>
        <li>
          <label for="title">Tiêu đề </label><input type="text" name="title" />
        </li>
        <!--
        <li>
           <label for="tieu_de">Tiêu Đề: </label><input type="text" name="tieu_de"/>
        </li>
      -->
        <li>
          <label for="body">Nội Dung: </label><textarea name="body"></textarea>
        </li>
      </ul>
    </form>
  </div>




<script type="text/javascript">
  
  jQuery(function($) {
      
  //var vl = $('#val_may').val();
  
  
  //alert('ID :'.vl));




   var $calendar = $('#calendar');
   //var id = 10;

   
   
   $calendar.weekCalendar({
      timeslotsPerHour : 2,
      allowCalEventOverlap : true,
      overlapEventsSeparate: true,
      firstDayOfWeek : 1,
      businessHours :{start: 1, end: 24, limitDisplay: false },
      daysToShow : 7,
      height : function($calendar) {
         return $(window).height() - $("h1").outerHeight() - 1;
      },
      eventRender : function(calEvent, $event) {
        //|| calEvent.start.getTime() < new Date().getTime()
         if (calEvent.end.getTime() < new Date().getTime()  ) {   //Check time start and time end < time hiện tại
            $event.css("backgroundColor", "#FC938F");
            $event.find(".wc-title").css({
               "backgroundColor" : "red",
               "border" : "1px solid red"

            });
         }

      },
      draggable : function(calEvent, $event) {
         return calEvent.readOnly != true;
      },
      resizable : function(calEvent, $event) {
         return calEvent.readOnly != true;
      },
      eventNew : function(calEvent, $event) {
      if(calEvent.start.getTime() < new Date().getTime()){
            //alert('aaaaaaaaaaaaaaaaa');
            var $dialogContent = $("#event_edit_container");
            $dialogContent.find("select[name='start']").attr("disabled", "disabled");
            
         }else{
             var $dialogContent = $("#event_edit_container");
            $dialogContent.find("select[name='start']").removeAttr("disabled");
            
         }
      if (calEvent.end.getTime() > new Date().getTime() && calEvent.start.getTime() > new Date().getTime() ) {   //Check time start and time end > time hiện tại
        
         var $dialogContent = $("#event_edit_container");

         resetForm($dialogContent);
         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         var titleField = $dialogContent.find("input[name='title']");
         var bodyField = $dialogContent.find("textarea[name='body']");
         var tieude= $dialogContent.find("input[name='tieu_de']");
  
    
            $dialogContent.dialog({
            modal: true,
            title: "Thông tin đặt lịch .",
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },
            buttons: {
               Đặt : function() {  
         var value=1;
        if(value==1){
                  // calEvent.id = id;
                  // id++;
                  // calEvent.start = new Date(startField.val());
                  // calEvent.end = new Date(endField.val());
                  // calEvent.title = titleField.val();
                  // calEvent.body = bodyField.val();

                  // //alert('aaaaaaaaaaaaaa');
                  // //alert(new Date(startField.val()));
                  // //alert(new Date(endField.val()));
                    var time_s=calEvent.start = new Date(startField.val()); 
                    var curr_date = time_s.getDate();
                    var curr_month = time_s.getMonth() + 1; //Months are zero based
                    var curr_year = time_s.getFullYear();
                    var curr_hour = time_s.getHours();
                    var curr_min = time_s.getMinutes();
                    //alert(curr_date + "-" + curr_month + "-" + curr_year);
                    var val_date_start= curr_year+"-"+curr_month+"-"+curr_date+" "+curr_hour+":"+curr_min+":01";


                    var time_e=calEvent.start = new Date(endField.val()); 
                    var curr_date = time_e.getDate();
                    var curr_month = time_e.getMonth() + 1; //Months are zero based
                    var curr_year = time_e.getFullYear();
                    var curr_hour = time_e.getHours();
                    var curr_min = time_e.getMinutes();
                    //alert(curr_date + "-" + curr_month + "-" + curr_year);
                    var val_date_end= curr_year+"-"+curr_month+"-"+curr_date+" "+curr_hour+":"+curr_min+":00";
                    //alert(val_date_start);
                    //them_lich

                     $.ajax({
                    type: "post",
                    url: <?php echo '"'.$base_url.'/ajax/them_lich.php"';?>,
                    data: {
                      id_lich:null,
                      id_may:<?php echo $id_may ?>,
                      id_user:  <?php echo $id_user ?>,
                      date_start:val_date_start,
                      date_end:val_date_end,
                      title: calEvent.title = titleField.val(),
                      content: calEvent.body = bodyField.val()
                      
                    },
                    contentType: "application/x-www-form-urlencoded",
                    success: function(responseData) {
                     // alert(responseData);
                      //var value_response= responseData;
                      if(responseData==1){
                         alert('Thời gian thay đổi phải lớn hơn thời gian hiện tại !!!');
                        return;
                      }
                      if(responseData==2){
                        alert('Đã có người đặt lịch vào khoảng thời gian bạn chọn');
                        return;
                      }else{
                      
                         $.ajax({
                              type: "post",
                              url: <?php echo '"'.$base_url.'/process.php"';?>,
                              data: {id:<?php echo $id_may; ?>},
                              contentType: "application/x-www-form-urlencoded",


                               beforeSend: function() {

                                 $("#status").show();

                                         },
                                  success: function(responseData, textStatus, jqXHR) {
                                      //alert("data saved")
                                      //alert(responseData);
                                     
                                      //$('#loading').hide();
                                       //$calendar.weekCalendar("removeUnsavedEvents");
                                       //$calendar.weekCalendar("updateEvent", calEvent);
                                       $("#status").hide();
                                       $dialogContent.dialog("close");
                                        alert('Bạn đã đặt lịch thành công !');
                                        $('#frm_content').html(responseData);
                                  },
                                  error: function(jqXHR, textStatus, errorThrown) {
                                      //console.log(errorThrown);
                                      alert(errorThrown);
                                       $('#loading').hide();
                                  }
                             })
                      }
                        
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        //console.log(errorThrown);
                        //alert(errorThrown);
                        // $('#loading').hide();
                    }
                });


          }
          else{
          alert('Đã có người đặt vào thời gian bạn chọn !!!!');
          }
               },
               Huỷ : function() {
                  $dialogContent.dialog("close");

               }
            }
         }).show();

         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));

      }
    else{
        alert('Bạn phải chọn thời gian hiện tại hoặc tương lai !!!!');
      
    }
    },
      eventDrop : function(calEvent, $event) {
        
      },
      eventResize : function(calEvent, $event) {
      },
      
      eventMouseover : function(calEvent, $event) {
      },
      eventClick : function(calEvent, $event) {

         if (calEvent.readOnly) {
          alert('Bạn chỉ có thể thay đổi lịch của cá nhân !');
            return;
         }

         if(calEvent.end < new Date() ){
          //alert('stop');
          return calEvent.readOnly != true;

         }
         if(calEvent.start.getTime() < new Date().getTime()){
            //alert('aaaaaaaaaaaaaaaaa');
            var $dialogContent = $("#event_edit_container");
            $dialogContent.find("select[name='start']").attr("disabled", "disabled");
            
         }else{
             var $dialogContent = $("#event_edit_container");
            $dialogContent.find("select[name='start']").removeAttr("disabled");
            
         }

         var time_ss=calEvent.start;
         var time_es=calEvent.end;
         //alert(calEvent.id);

         var $dialogContent = $("#event_edit_container");
         resetForm($dialogContent);
         
         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);

         var titleField = $dialogContent.find("input[name='title']").val(calEvent.tieu_de);

         var bodyField = $dialogContent.find("textarea[name='body']").val(calEvent.body);

        // var tieude= $dialogContent.find("input[name='tieu_de']").val(calEvent.tieu_de);

         bodyField.val(calEvent.body);

         $dialogContent.dialog({
            modal: true,
            title: "Sửa lịch - " + calEvent.title,
            close: function() {
               $dialogContent.dialog("destroy");
               $dialogContent.hide();
               $('#calendar').weekCalendar("removeUnsavedEvents");
            },
            buttons: {
               Sửa : function() {

                    var time_batdau_cu=calEvent.start = new Date(time_ss); 
                    var curr_date = time_batdau_cu.getDate();
                    var curr_month = time_batdau_cu.getMonth() + 1; //Months are zero based
                    var curr_year = time_batdau_cu.getFullYear();
                    var curr_hour = time_batdau_cu.getHours();
                    var curr_min = time_batdau_cu.getMinutes();
                    var curr_sec= time_batdau_cu.getSeconds();
                    //alert(curr_date + "-" + curr_month + "-" + curr_year);
                    var val_time_S= curr_year+"-"+curr_month+"-"+curr_date+" "+curr_hour+":"+curr_min+":01";


                    var time_ketthuc_cu=calEvent.start = new Date(time_es); 
                    var curr_date = time_ketthuc_cu.getDate();
                    var curr_month = time_ketthuc_cu.getMonth() + 1; //Months are zero based
                    var curr_year = time_ketthuc_cu.getFullYear();
                    var curr_hour = time_ketthuc_cu.getHours();
                    var curr_min = time_ketthuc_cu.getMinutes();
                    var curr_sec= time_ketthuc_cu.getSeconds();
                    //alert(curr_date + "-" + curr_month + "-" + curr_year);
                    var val_date_end_change= curr_year+"-"+curr_month+"-"+curr_date+" "+curr_hour+":"+curr_min+":"+curr_sec;
                    //alert(val_date_start);






                 var time_s=calEvent.start = new Date(startField.val()); 
                    var curr_date = time_s.getDate();
                    var curr_month = time_s.getMonth() + 1; //Months are zero based
                    var curr_year = time_s.getFullYear();
                    var curr_hour = time_s.getHours();
                    var curr_min = time_s.getMinutes();
                    //alert(curr_date + "-" + curr_month + "-" + curr_year);
                    var val_date_start= curr_year+"-"+curr_month+"-"+curr_date+" "+curr_hour+":"+curr_min+":01";


                    var time_e=calEvent.start = new Date(endField.val()); 
                    var curr_date = time_e.getDate();
                    var curr_month = time_e.getMonth() + 1; //Months are zero based
                    var curr_year = time_e.getFullYear();
                    var curr_hour = time_e.getHours();
                    var curr_min = time_e.getMinutes();
                    //alert(curr_date + "-" + curr_month + "-" + curr_year);
                    var val_date_end= curr_year+"-"+curr_month+"-"+curr_date+" "+curr_hour+":"+curr_min+":00";
                    //alert(val_date_start);


                  $.ajax({
                    type: "post",
                    url: <?php echo '"'.$base_url.'/ajax/sua_lich.php"';?>,
                    data: {
                      id_lich:calEvent.id,
                      id_may:<?php echo $id_may ?>,
                      id_user:  <?php echo $id_user ?>,
                      date_start:val_date_start,
                      date_end:val_date_end,
                      title: calEvent.title = titleField.val(),
                      content: calEvent.body = bodyField.val(),
                      time_s:val_time_S,
                      time_e:val_date_end_change
                    },
                    contentType: "application/x-www-form-urlencoded",
                    success: function(responseData) {

                     // alert(responseData);
                      //var value_response= responseData;
                       if(responseData==1){
                        alert('Thời gian thay đổi phải lớn hơn thời gian hiện tại !!!');
                        return;
                      }
                      if(responseData==2){
                        alert('Đã có người đặt lịch vào khoảng thời gian bạn chọn !!!');
                        return;
                      }
                      else{
                      
                         $.ajax({
                              type: "post",
                              url: <?php echo '"'.$base_url.'/process.php"';?>,
                              data: {id:<?php echo $id_may; ?>},
                              contentType: "application/x-www-form-urlencoded",


                               beforeSend: function() {

                                 $("#status").show();

                                         },
                                  success: function(responseData, textStatus, jqXHR) {
                                      //alert("data saved")
                                      //alert(responseData);
                                     
                                      //$('#loading').hide();
                                       //$calendar.weekCalendar("removeUnsavedEvents");
                                       //$calendar.weekCalendar("updateEvent", calEvent);

                                       $("#status").hide();
                                       $dialogContent.dialog("close");
                                        //alert('Thay đổi lịch thành công !');
                                        $('#frm_content').html(responseData);
                                  },
                                  error: function(jqXHR, textStatus, errorThrown) {
                                      //console.log(errorThrown);
                                      alert(errorThrown);
                                       $('#loading').hide();
                                  }
                             })
                      }
                        
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        //console.log(errorThrown);
                        //alert(errorThrown);
                        // $('#loading').hide();
                    }
                });
                  //$calendar.weekCalendar("updateEvent", calEvent);
                  //$dialogContent.dialog("close");

               },
               "Xoá" : function() {
                if(calEvent.start.getTime() < new Date().getTime()){
                    alert('Bạn không thể xoá khi đã bắt đầu lịch !');
                    return;
                }


                 if (confirm("Bạn có chắc chắn muốn xoá  lịch?")) {
                    $.ajax({
                    type: "post",
                    url: <?php echo '"'.$base_url.'/ajax/xoa_lich.php"';?>,
                    data: {
                      id_lich:calEvent.id
                    },
                    contentType: "application/x-www-form-urlencoded",
                    success: function(responseData) {

                     // alert(responseData);
                      //var value_response= responseData;
                       if(responseData==3){
                      
                         $.ajax({
                              type: "post",
                              url: <?php echo '"'.$base_url.'/process.php"';?>,
                              data: {id:<?php echo $id_may; ?>},
                              contentType: "application/x-www-form-urlencoded",


                               beforeSend: function() {

                                 $("#status").show();

                                         },
                                  success: function(responseData, textStatus, jqXHR) {
                                      //alert("data saved")
                                      //alert(responseData);
                                     
                                      //$('#loading').hide();
                                       //$calendar.weekCalendar("removeUnsavedEvents");
                                       //$calendar.weekCalendar("updateEvent", calEvent);

                                       $("#status").hide();
                                       $dialogContent.dialog("close");
                                        alert('Xoá lịch thành công !');
                                        $('#frm_content').html(responseData);
                                  },
                                  error: function(jqXHR, textStatus, errorThrown) {
                                      //console.log(errorThrown);
                                      alert(errorThrown);
                                       $('#loading').hide();
                                  }
                             })
                      }
                        
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        //console.log(errorThrown);
                        //alert(errorThrown);
                        // $('#loading').hide();
                    }
                });
                    }
                  return false;

                  //alert(calEvent.id);
                  //$calendar.weekCalendar("removeEvent", calEvent.id);
                  //$dialogContent.dialog("close");
               }
            }
         }).show();

         var startField = $dialogContent.find("select[name='start']").val(calEvent.start);
         var endField = $dialogContent.find("select[name='end']").val(calEvent.end);
         $dialogContent.find(".date_holder").text($calendar.weekCalendar("formatDate", calEvent.start));
         setupStartAndEndTimeFields(startField, endField, calEvent, $calendar.weekCalendar("getTimeslotTimes", calEvent.start));
         $(window).resize().resize(); //fixes a bug in modal overlay size ??

      },
      eventMouseout : function(calEvent, $event) {
      },
      noEvents : function() {

      },
      data : function(start, end, callback) {
         callback(getEventData());
      }
   });

   function resetForm($dialogContent) {
      $dialogContent.find("input").val("");
      $dialogContent.find("textarea").val("");
   }

   function getEventData() {
      var year = new Date().getFullYear();

      var month = new Date().getMonth();

      var day = new Date().getDate();

      //alert(new Date().getMonth());
      //alert( new Date(2013, month, day, 2));


      return {
         events : [
         <?php
          foreach ($arr_lich as $lich)
                    {

                      $id = $lich->id_lich;
                        $string_start = $lich->ngay_batdau;
                        $timestart = strtotime($string_start);
                        $date_s=date("d", $timestart);
                        $month_s=date("m", $timestart)-1;
                        $year_s=date("Y", $timestart);
                        $hour_s=date("H", $timestart);
                        $min_s=date("i", $timestart);


                        $string_end = $lich->ngay_ket_thuc;
                        $timeend = strtotime($string_end);
                        $date_e=date("d", $timeend);
                        $month_e=date("m", $timeend)-1;
                        $year_e=date("Y", $timeend);
                        $hour_e=date("H", $timeend);
                        $min_e=date("i", $timeend);

                      $status="true";
                      $div_open="";
                      $div_close="";
                      if($lich->ID==$id_user){
                        $status="false";
                        $div_open="<div class='active'>";
                        $div_close="</div>";
                      }

       $id_user_meta_data = $wpdb->get_results("SELECT * FROM wp_usermeta WHERE user_id = ".$id_user);

                     foreach ($id_user_meta_data as $key =>$vlue) 
                         {
                                                       
                           if ($vlue ->meta_value == 'a:1:{s:13:"administrator";b:1;}'  ) // or $vlue ->meta_value == 'a:1:{s:13:"administrator";b:1;}'
                             {
                                 $status="false";
                             }
                            if ($vlue ->meta_value == 'a:1:{s:6:"editor";b:1;}'  ) 
                               {
                                 $status="false";
                              }
                          }

        
                      echo '{
                           "id":'."'".$id."'".',
                           "start": new Date('.$year_s.', '.$month_s.', '.$date_s.', '.$hour_s.','.$min_s.'),
                           "end": new Date('.$year_e.', '.$month_e.', '.$date_e.', '.$hour_e.', '.$min_e.'),
                            "title":'.'"'.$lich->user_login.'",
                            "tieu_de": '.'"'.$lich->tieu_de_lich .'",
                            "body":'.'"'.$lich->noi_dung_lich.'",
                            readOnly : '.$status.'
                      },';
                    }
          ?>
            //  {
            //    "id":4,
            //    "start": new Date(year, month, day , 18),
            //    "end": new Date(year, month, day , 20),
            //    "title":"Tên test",
            //    "tieu_de":"alo alo",
            //    "body":"content demo"

            // },
            // {
            //    "id":5,
            //    "start": new Date(year, month, day , 16),
            //    "end": new Date(year, month, day , 17),
            //    "title":"Tên user"
            // },
            // {
            //    "id":6,
            //    "start": new Date(year, month, day, 12),
            //    "end": new Date(year, month, day, 14),
            //    "title":"I'm read-only",
            //    readOnly : true
            // }

         ]
      };
   }


   /*
    * Sets up the start and end time fields in the calendar event
    * form for editing based on the calendar event being edited
    */
   function setupStartAndEndTimeFields($startTimeField, $endTimeField, calEvent, timeslotTimes) {

      for (var i = 0; i < timeslotTimes.length; i++) {
         var startTime = timeslotTimes[i].start;
         var endTime = timeslotTimes[i].end;
         var startSelected = "";
         if (startTime.getTime() === calEvent.start.getTime()) {
            startSelected = "selected=\"selected\"";
         }
         var endSelected = "";
         if (endTime.getTime() === calEvent.end.getTime()) {
            endSelected = "selected=\"selected\"";
         }
         $startTimeField.append("<option value=\"" + startTime + "\" " + startSelected + ">" + timeslotTimes[i].startFormatted + "</option>");
         $endTimeField.append("<option value=\"" + endTime + "\" " + endSelected + ">" + timeslotTimes[i].endFormatted + "</option>");

      }
      $endTimeOptions = $endTimeField.find("option");
      $startTimeField.trigger("change");
   }

   var $endTimeField = $("select[name='end']");
   var $endTimeOptions = $endTimeField.find("option");

   //reduces the end time options to be only after the start time options.
   $("select[name='start']").change(function() {
      var startTime = $(this).find(":selected").val();
      var currentEndTime = $endTimeField.find("option:selected").val();
      $endTimeField.html(
            $endTimeOptions.filter(function() {
               return startTime < $(this).val();
            })
            );

      var endTimeSelected = false;
      $endTimeField.find("option").each(function() {
         if ($(this).val() === currentEndTime) {
            $(this).attr("selected", "selected");
            endTimeSelected = true;
            return false;
         }
      });

      if (!endTimeSelected) {
         //automatically select an end date 2 slots away.
         $endTimeField.find("option:eq(1)").attr("selected", "selected");
      }

   });


   var $about = $("#about");

   $("#about_button").click(function() {
      $about.dialog({
         title: "About this calendar demo",
         width: 600,
         close: function() {
            $about.dialog("destroy");
            $about.hide();
         },
         buttons: {
            close : function() {
               $about.dialog("close");
            }
         }
      }).show();
   });

  });





























</script>